package cn.hxzy.zyicon.controller;

import cn.hxzy.zyicon.entity.Role;
import cn.hxzy.zyicon.entity.User;
import cn.hxzy.zyicon.entity.po.UserPO;
import cn.hxzy.zyicon.entity.vo.PageBean;
import cn.hxzy.zyicon.entity.vo.ReturnBean;
import cn.hxzy.zyicon.service.RoleService;
import cn.hxzy.zyicon.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @PostMapping("searchName")
    public ReturnBean searchName(String searchName,@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer size) {
        PageBean<User> all = userService.findUserByNameLike(searchName,new PageBean<User>(page, size));
        return ReturnBean.of(ReturnBean.AnswerCode.SUCCESS, all);
    }
    @PostMapping("list")
    public ReturnBean list(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer size) {
        PageBean<User> all = userService.findAll(new PageBean<User>(page, size));
        return ReturnBean.of(ReturnBean.AnswerCode.SUCCESS, all);
    }

    @PostMapping("add")
    public ReturnBean add(User user,Integer roleId) {
        Role role=new Role();
        role.setId(roleId);
        user.setRole(role);
        userService.save(user);
        return ReturnBean.of(ReturnBean.AnswerCode.SUCCESS);
    }

    @PostMapping("roleList1")
    public ReturnBean roleList1() {
        List<Role> all = roleService.findAll();
        return ReturnBean.of(ReturnBean.AnswerCode.SUCCESS,all);
    }

    @PostMapping("deleteId")
    public ReturnBean deleteId(Integer id) {
        userService.delete(id);
        return ReturnBean.of(ReturnBean.AnswerCode.SUCCESS);
    }
    @PostMapping("update")
    public ReturnBean update(UserPO userPO) {
        User user=new User();
        BeanUtils.copyProperties(userPO,user);
        Role role = new Role();
        role.setId(userPO.getRoleId());
        user.setRole(role);
        userService.update(user);
        return ReturnBean.of(ReturnBean.AnswerCode.SUCCESS);
    }
    @PostMapping("findById")
    public ReturnBean findById(Integer id) {
        User byId = userService.findById(id);
        return ReturnBean.of(ReturnBean.AnswerCode.SUCCESS,byId);
    }

}
